//购物车模块
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from "./userStore";
import {delCartAPI, findNewCartListAPI, insertCartAPI} from "@/apis/cart"


export const useCartStore = defineStore('cart', () => {
  //获取最新购物车列表action
  const updateNewList = async () => {
    const res = await findNewCartListAPI()
    cartList.value = res.result    
  }
  const userStore = useUserStore()
  const isLogin = computed(() => userStore.userInfo.token)
  //1.定义state-cartList
  const cartList = ref([])
  //2.定义action方法-addCart

  //添加购物车操作
  const addCart = async (goods) => {
    //已经添加过，count+1, 否则push
    //通过匹配传递过来的skuId能不能在cartList找到过
    const {skuId, count} = goods
    if(isLogin.value) {
      //登陆之后的逻辑
      await insertCartAPI({skuId, count})
      updateNewList()
    } else {
      const item = cartList.value.find((item) => goods.skuId === item.skuId)
      if(item) {
        //找到
        item.count = item.count + goods.count
      } else {
        cartList.value.push(goods)
      }      
    }

  }
  //删除购物车
  const delCart = async (skuId) => {
    //1.在数组中删除，或者找下标值 - splice
    //2.使用数组过滤 - filter
    if(isLogin.value) {
      //调用接口实现购物车的删除功能
      delCartAPI([skuId])
      //获取购物车
      updateNewList()
    } else {
      const index = cartList.value.findIndex((item) => skuId === item.skuId)
      cartList.value.splice(index, 1)      
    }
  }
  //清空购物车
  const clearCart = () => {
    cartList.value = []
  }
  //单选功能
  const singleCheck = (skuId, selected) => {
    //通过skuId找到selected
    const item = cartList.value.find((item) => (item.skuId) == skuId);
    item.selected = selected;
  }
  //全选功能
  const allcheck = (selected) => {
    //把cartList中的每一项都设置成当前的全选框功能
    cartList.value.forEach((item) => item.selected = selected)
  }
  //计算属性
  //1.总的数量 所有项的count之和
  const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))
  //2.总价 所有项的count*price
  const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0))
  //3.全选
  // const isAll = computed(() => (cartList.value.reduce((a, c) => a + c.selected ===true, 0) == cartList.value.length))
  const isAll = computed(() => (cartList.value.every((item) => item.selected)))
  //3.已经选择的商品数量
  const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
  //4.已经选择的商品价钱合计
  const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count* c.price, 0))
  return {
    allCount,
    allPrice,
    isAll,
    selectedCount,
    selectedPrice,
    cartList,
    addCart,
    delCart,
    clearCart,
    updateNewList,
    singleCheck,
    allcheck
  }
},
  {
    persist: true
  }
)